// API配置文件
import axios from 'axios';
import { userStorage } from '@/utils/storage';
import { showLoading, hideLoading } from '@/utils/loadingStore';

// API域名配置
export const API_DOMAINS = {
  // 开发环境 - 使用Vite代理配置的目标域名
  development: '',
  // 生产环境 - 使用相对路径，利用前端站点的反向代理
  production: '',
  // 微信小程序环境 - 使用实际的API域名
  miniprogram: 'https://static.shixiaoquan.com'
};

// 图片基础URL配置
const IMAGE_BASE_URL = 'https://site.shixiaoquan.com';

// 图片URL生成函数
export const getImageUrl = (imagePath) => {
  if (!imagePath) return '';
  
  // 如果已经是完整的URL，直接返回
  if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
    return imagePath;
  }
  
  // 直接使用 IMAGE_BASE_URL 变量进行地址拼接
  return `${IMAGE_BASE_URL}${imagePath}`;
}

// API配置
export const API_CONFIG = {
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
};

// 获取baseURL的函数
export const getBaseURL = () => {
  // 检查是否在uni-app环境
  if (typeof uni !== 'undefined') {
    // 检查是否在H5环境（浏览器中运行的uni-app）
    if (typeof window !== 'undefined' && window.location) {
      const isDev = process.env.NODE_ENV === 'development';
      const isLocalhost = window.location.origin.includes('localhost');
      
      if (isDev && isLocalhost) {
        // 开发环境使用代理避免CORS
        return '';
      } else {
        // 生产环境或非本地环境
        return isDev ? API_DOMAINS.development : API_DOMAINS.production;
      }
    }
    
    // 检查uni-app的平台信息（非H5环境）
    try {
      const platform = uni.getSystemInfoSync().platform;
      
      // 如果是在微信小程序中运行的uni-app
      if (platform === 'devtools' || typeof __wxConfig !== 'undefined') {
        return API_DOMAINS.miniprogram;
      }
    } catch (e) {
      console.log('获取uni-app平台信息失败:', e);
    }
    
    // 其他uni-app环境（如APP等）
    const isDev = process.env.NODE_ENV === 'development';
    return isDev ? API_DOMAINS.development : API_DOMAINS.production;
  }
  
  // 普通web环境
  if (typeof window !== 'undefined') {
    const isDev = process.env.NODE_ENV === 'development';
    const isLocalhost = window.location.origin.includes('localhost');
    
    if (isDev && isLocalhost) {
      // 开发环境使用代理
      return ''; // 使用Vite代理
    } else {
      // 生产环境或非本地开发环境
      return isDev ? API_DOMAINS.development : API_DOMAINS.production;
    }
  }
  
  // 默认返回生产环境域名
  return API_DOMAINS.production;
};

// 创建 axios 实例
export const axiosInstance = axios.create({
  baseURL: getBaseURL(),
  timeout: API_CONFIG.timeout,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

// 配置uni-app适配器
if (typeof uni !== 'undefined') {
  const isH5 = typeof window !== 'undefined' && window.location;
  const isDev = process.env.NODE_ENV === 'development';
  const isLocalhost = isH5 && window.location.origin.includes('localhost');
  
  // H5开发环境使用原生axios，其他环境使用uni.request适配器
  if (isH5 && isDev && isLocalhost) {
    // H5开发环境使用原生axios + Vite代理
  } else {
    // 其他环境使用uni.request适配器
    axiosInstance.defaults.adapter = function(config) {
      return new Promise((resolve, reject) => {
        // 构建完整URL
        let fullUrl = config.url;
        if (!fullUrl.startsWith('http') && config.baseURL) {
          fullUrl = config.baseURL + config.url;
        }
        
        // 准备请求参数
        const requestConfig = {
          url: fullUrl,
          method: config.method.toUpperCase(),
          header: config.headers || {},
          timeout: config.timeout || 10000,
          success: (res) => {
            resolve({
              data: res.data,
              status: res.statusCode,
              statusText: res.statusCode === 200 ? 'OK' : 'Error',
              headers: res.header || {},
              config: config
            });
          },
          fail: (err) => {
            reject(new Error(err.errMsg || 'Network Error'));
          }
        };
        
        // 添加请求数据
        if (config.data) {
          if (config.method.toLowerCase() === 'get') {
            requestConfig.data = config.data;
          } else {
            requestConfig.data = config.data;
          }
        }
        
        // 发起请求
        uni.request(requestConfig);
      });
    };
  }
}

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    try {
      // 显示全局加载
      showLoading('请求中...');
      
      // 添加token
      const token = userStorage.getToken();
      if (token) {
        config.headers.token = token;
      }
      
      return config;
    } catch (error) {
      console.error('❌ 请求拦截器错误:', error);
      hideLoading();
      throw error;
    }
  },
  (error) => {
    hideLoading();
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    try {
      hideLoading();
      
      const data = response.data;
      
      // 全局登录过期检查：当code=0且data=-1时，表示登录过期
      if (data.code === 0 && data.data === -1) {
        // 显示登录过期提示
        uni.showModal({
          title: '⚠️ 登录已过期',
          content: '您的登录状态已过期，请重新登录以继续使用。',
          confirmText: '立即登录',
          cancelText: '稍后再说',
          confirmColor: '#FF5151',
          cancelColor: '#999999',
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              // 清除本地登录状态
              userStorage.clearUserInfo();
              // 跳转到登录页
              uni.reLaunch({ url: '/pages/login/login' });
            }
          }
        });
        // 抛出错误，阻止后续处理
        throw new Error('登录已过期');
      }
      
      // 根据不同接口的响应格式处理
      if (data.hasOwnProperty('success')) {
        // 格式1：使用success字段
        if (!data.success) {
          const errorMsg = data.msg || data.message || '请求失败';
          throw new Error(errorMsg);
        }
      } else if (data.hasOwnProperty('code')) {
        // 格式2：使用code字段，判断成功条件（兼容0/1/200，数字或字符串）
        const code = data.code;
        const okCodes = new Set([0, 1, 200, '0', '1', '200']);
        if (!okCodes.has(code)) {
          const errorMsg = data.msg || data.message || ERROR_CODES[code] || '请求失败';
          throw new Error(errorMsg);
        }
      }
      
      return data;
    } catch (error) {
      hideLoading();
      throw error;
    }
  },
  (error) => {
    hideLoading();
    
    let errorMsg = '网络错误';
    
    if (error.name === 'TypeError' && error.message.includes('fetch')) {
      errorMsg = '网络连接失败，请检查网络';
    } else if (error.message) {
      errorMsg = error.message;
    }
    
    throw new Error(errorMsg);
  }
);

// API端点
export const API_ENDPOINTS = {
  // 短信相关
  SMS: {
    SEND_CODE: '/api/index/sendMsgCode'
  },
  
  // 首页相关接口
  INDEX: {
    GET_BANNER_LIST: '/api/index/getBannerList',
    GET_MENU_LIST: '/api/index/getMenuList',
    UPLOAD_FILE: '/api/index/uploadFile',
    GET_NOTICE_LIST: '/api/index/getNoticeList',
    GET_NOTICE_INFO: '/api/index/getNoticeInfo',
    GET_USER_NO_READ_MSG_LIST: '/api/index/getUserNoReadMsgList',
    GET_USER_NO_READ_MSG_COUNT: '/api/index/getUserNoReadMsgCount',
    SET_NOTICE_READ: '/api/index/setNoticeRead',
    SET_ALL_NOTICE_READ: '/api/index/setAllNoticeRead',
    // 文章相关接口
    ALL_ARTICLE_TYPE: '/api/index/allArticleType',
    FIND_ARTICLES: '/api/index/findArticles',
    FIND_ARTICLE_BY_ID: '/api/index/findArticleById'
  },
  
  // 用户相关
  USER: {
    LOGIN: '/api/index/login',
    LOGIN_BY_MSG_CODE: '/api/index/loginByMsgCode',
    LOGIN_BY_PHONE: '/api/index/loginByPhone',
    REGISTER: '/api/index/register',
    PROFILE: '/api/user/profile',
    GET_INFO: '/api/user/getUserInfo',
    CHANGE_INFO: '/api/user/changeUserInfo',
    CHANGE_MOBILE: '/api/user/changeMobile',
    BIND_MOBILE: '/api/user/bandMobile',
    LOGOUT: '/api/user/logout',
    GET_USER_ACCOUNT_LOG: '/api/user/getUserAccountLog',
    GET_WITHDRAW_LOG: '/api/user/getWithdrawLog',
    BIND_ALIPAY: '/api/user/bindAlipay',
    MY_TEAM_LIST: '/api/user/myTeamList',
    REAL_NAME_TWO: '/api/user/realNameTwo',
    WITHDRAW: '/api/user/withdraw',
    RECHARGE: '/api/user/recharge',
    RECHARGE_PAY: '/api/user/rechargePay'
  },

  // 微信相关
  WECHAT: {
    GET_WX_LOGIN_CODE: '/api/wechat/getWxLoginCode',
    WX_LOGIN: '/api/wechat/wxLogin'
  },

  // 商品相关
  GOODS: {
    GET_GOODS_CLASS: '/api/goods/getGoodsClass',
    GET_GOODS_LIST: '/api/goods/getGoodsList',
    GET_GOODS_INFO: '/api/goods/getGoodsInfo',
    GET_GOODS_BY_CLASS: '/api/goods/getGoodsByClass',
    CREATE_ORDER: '/api/goods/createOrder',
    ADD_GOODS: '/api/goods/addGoods',
    USER_ORDER_LIST: '/api/goods/userOrderList',
    USER_ORDER_INFO: '/api/goods/userOrderInfo',
    USER_ORDER_PAY: '/api/goods/orderPay',
    FIND_GRAB_ORDER_BY_USER: '/api/goods/findGrabOrderByUser',

    GET_CLASS_BY_TYPE: '/api/goods/getClassByType',
    GET_GOODS_SPECS: '/api/goods/getGoodsSpecs',
    GET_GOODS_TEMPS: '/api/goods/getGoodsTemps',
    FIND_ALL_CARMINE_BY_USER: '/api/goods/findAllCarmineByUser',
    GRAB_ORDER: '/api/goods/grabOrder',
    CONFIRM_GRAB_ORDER: '/api/goods/confirmGrabOrder',
    RESERVATION_GOODS: '/api/goods/reservationGoods',
    CHANNEL_LIST: '/api/goods/channelList',
    CHANGE_ORDERS_TYPE: '/api/goods/changeOrdersType',
    ABANDON_ORDER: '/api/goods/abandonOrder',
    ORDER_CANCEL: '/api/goods/orderCancel',
    CONFIRM_ORDER: '/api/goods/confirmOrder',
    SHELF_CARMINS: '/api/goods/shelfCarmins',
    CHANGE_CARMINE_PRICE: '/api/goods/changeCarminePrice'
  },

  // 订单相关
  ORDER: {
    GET_CARMINES: '/api/goods/getCarmines',
    OBJECTION_ORDER: '/api/goods/objectionOrder',
    GET_TRADE_NOTICE_LIST: '/api/goods/getTradeNoticeList',
    GET_BUY_ORDER_NOTICE: '/api/goods/getBuyOrderNotice',
    GET_SELL_ORDER_NOTICE: '/api/goods/getSellOrderNotice',
    MARK_TRADE_NOTICE_READ: '/api/goods/markTradeNoticeRead'
  }
};

// 错误码配置
export const ERROR_CODES = {
  SUCCESS: 200,
  TOKEN_EXPIRED: 401,
  TOKEN_INVALID: 403,
  200: '成功',
  400: '请求参数错误',
  401: '未授权',
  403: '禁止访问',
  404: '资源不存在',
  500: '服务器内部错误',
  502: '网关错误',
  503: '服务不可用'
};

export default {
  API_CONFIG,
  API_ENDPOINTS,
  ERROR_CODES,
  IMAGE_BASE_URL,
  getImageUrl,
  getBaseURL,
  axiosInstance
};